package redis;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import util.RedisUtil;

import javax.annotation.Resource;

/**
 * 缓存失效
 *
 * @author zhanglinfeng
 * @date create in 2022/8/31 11:17
 */
@Aspect
public class RedisExpireAspect implements Ordered {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisExpireAspect.class);

    @Resource
    private RedissonClient redissonClient;

    @Override
    public int getOrder() {
        return 4;
    }

    @Pointcut("@annotation(redis.RedisExpire)")
    public void pointcut() {
    }

    @After(value = "pointcut()&&@annotation(redisExpire)")
    public void doAspect(JoinPoint joinPoint, RedisExpire redisExpire) {
        // 获取缓存key
        String cacheKey = RedisUtil.getKey(joinPoint.getArgs(), redisExpire.cacheKey(), redisExpire.cacheIndex());
        //失效
        RBucket<Object> rBucket = redissonClient.getBucket(cacheKey);
        if (rBucket.isExists()) {
            rBucket.delete();
            LOGGER.info("缓存失效，key：{}", cacheKey);
        }
    }
}
